/*************************************************************************
	> File Name: test8.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023年08月23日 星期三 18时41分09秒
 ************************************************************************/
#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <unistd.h>
#include <stdlib.h>

typedef void (*handler_t)();

std::vector<handler_t> handlers;

void fun_one() {
    printf("This is a temp task1\n");
}

void fun_two() {
    printf("This is a temp task2\n");
}

void Load() {
    handlers.push_back(fun_one);
    handlers.push_back(fun_two);
}

int main() {
    pid_t id = fork();
    if (id < 0) {
        perror("fork");
        exit(-1);
    } else if (id == 0) {
        int cnt = 15;
        while (cnt) {
            printf("I' m the child process:%d, pid[%d]\n", cnt--, getpid());
            sleep(1);
        }
        exit(11);
    } else {
        int quit = 0;
        while (!quit) {
            int status = 0;
            pid_t  res = waitpid(-1, &status, WNOHANG);
            if (res > 0) {
                printf("Wait the Child process success, exit code:%d\n", WEXITSTATUS(status));
                quit = 1;
            }
            else if (res == 0) {
                printf("Wait the Child process success, but the child process is going\n");
                if (handlers.empty()) Load();
                for (auto iter : handlers)  iter();
            } else {
                printf("Wait the Child process failure\n");
                quit = 1;
            }
        }
    }
    return 0;
}
